<template>
  <el-button-group style="margin-bottom: 5px">
    <el-button
        type="primary"
        :icon="MapLocation"
        color="#cdcdcd"
        @click="locationHandle"
    >
      点我定位
    </el-button>
    <el-button
        type="primary"
        :icon="Place"
        style="margin-left: 5px"
        color="#202020"
        @click="nearbyHeritageHandle"
    >
      查寻附近
    </el-button>
  </el-button-group>
  <el-input v-model="searchDistance" style="width: 120px;margin-bottom: 5px" placeholder="距离">
    <template #append>km</template>
  </el-input>
  <div style="display: flex">
    <div ref="main" style="width:90%;height:800px;border: 1px solid;"></div>
    <div>
      <el-radio-group
          v-model="radio"
          style="display: flex;flex-direction: column;margin-left: 20px"
          @change="handleCategory"
      >
        <el-radio-button
            :label="0"
        >
          全部
        </el-radio-button>
        <el-radio-button
            v-for="category in categoryList"
            :label="category.id"
        >
          {{ category.name }}
        </el-radio-button>
      </el-radio-group>
    </div>
  </div>
</template>

<script setup>

import * as echarts from 'echarts';
import 'echarts/extension/bmap/bmap';
import {getCurrentInstance, onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import {useHeritageStore} from "../store/useHeritageStore.js";
import {useUserStore} from "../store/useUserStore.js";
import {MapLocation,Place} from '@element-plus/icons-vue'
// import geoCoordMap from '../util/geoCoordMap.js'
// import mapData from "../util/mapData.js";


const {proxy} = getCurrentInstance()
const router = useRouter()
const heritageStore = useHeritageStore()
const userStore = useUserStore()
const radio = ref(0)
const categoryList = ref([])
const mapData = ref([])
const geoCoordMap = ref({})
const zoom = ref(5)
const bmapCenter = ref([116.20,39.56])
const flag = ref(false)
const searchDistance = ref(200)
const dataColor = ref('#ff0000')
let myChart

//查找附近非遗
const nearbyHeritageHandle = () => {
  if (!flag.value){
    proxy.$notify({
      title: 'Warning',
      message: '请先点击点我定位',
      type: 'warning',
      duration:2500
    })
    return
  }
  if (searchDistance.value <= 0){
    proxy.$notify({
      title: 'Warning',
      message: '距离至少大于0',
      type: 'warning',
      duration:2500
    })
    return
  }

  proxy.request.get('/api/kGraph', {
    params: {
      lat: Number(userStore.user.point.y),
      lon: Number(userStore.user.point.x),
      distance:searchDistance.value,
      categoryId:radio.value
    }
  }).then(res => {
    if (res.code === '1'){
      zoom.value = 6
      bmapCenter.value = [Number(userStore.user.point.x), Number(userStore.user.point.y)]
      convertMapData(res.data)
    }else{
      proxy.$message.error(res.msg)
    }
  })
}

//自我定位
const locationHandle = () => {
  flag.value = true
  const params = {
    name: 'Top 5',
    type: 'effectScatter',
    coordinateSystem: 'bmap',
    data: [
      {
        name:'我',
        value:[userStore.user.point.x,userStore.user.point.y]
      }
    ],
    symbolSize: 35,
    encode: {
      value: 2
    },
    showEffectOn: 'render',
    rippleEffect: {
      brushType: 'stroke'
    },
    label: {
      formatter: '我',
      position: 'right',
      show: true
    },
    itemStyle: {
      shadowBlur: 10,
      shadowColor: '#333'
    },
    emphasis: {
      scale: true
    },
    zlevel: 1
  }
  timer(params)
}


//转换数据
const convertMapData = (data) => {
  const tempData = data.filter(h => !h.location.includes('error'))
  mapData.value = tempData.map(h => {
    let city = h.city
    if (city.includes('市')) {
      city = city.substring(0, city.length - 1)
    }
    const tempMapData = {
      name: city,
      value: h.name + '@' + h.id,
    }
    const arr = h.location.split(',')
    const lon = Number(arr[1])
    const lat = Number(arr[0])
    const tempLocation = [Math.floor(lon * 100) / 100, Math.floor(lat * 100) / 100]
    // Reflect.set(geoCoordMap.value, h.city, tempLocation) // 动态给对象新增属性
    geoCoordMap.value[city] = tempLocation
    return tempMapData
  })
  timer()
}
//切换分类
const handleCategory = () => {
  // 准备数据颜色组
  const colors = ['#5470c6','#499c54','#e9bd69','#24e1f6','#fda5d7','#07b4f4','#ff9800','#800000','#800000','#BDB76B','#f87f6c']
  dataColor.value = colors[radio.value]
  proxy.request.get(`/api/heritage/category/${radio.value}`).then(res => {
    if (res.code === '1') {
      convertMapData(res.data)
    } else {
      proxy.$message.error(res.msg)
    }
  })
}
handleCategory()

//查询分类列表
const queryCategoryList = () => {
  proxy.request.get('/api/category/queryCategoryList').then(res => {
    if (res.code === '1') {
      categoryList.value = res.data
    }
  })
}
queryCategoryList()

const timer = (params) => {
  if (myChart != null && myChart != "" && myChart != undefined) {
    myChart.dispose();//销毁
  }
  myChart = echarts.init(proxy.$refs.main);
  let option;

  const convertData = (mapData) => {
    let data = mapData.value
    let res = [];

    for (let i = 0; i < data.length; i++) {
      let geoCoord = geoCoordMap.value[data[i].name];
      if (geoCoord) {
        res.push({
          name: data[i].name,
          value: geoCoord.concat(data[i].value)
        });
      }
    }
    return res;
  };
  option = {
    title: {
      text: 'Basic Graph',
      subtext: 'data from Internet',
      left: 'left'
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        if (params.data.name === '我'){
          return '我'
        }else{
          return '非遗名称：' + params.data.value[2].substring(0,params.data.value[2].indexOf('@'))
        }
      }
    },
    bmap: {
      center: bmapCenter.value,
      zoom: zoom.value,
      roam: true,
      mapStyle: {
        // styleJson: [
        //   {
        //     featureType: 'water',
        //     elementType: 'all',
        //     stylers: {
        //       color: '#d1d1d1'
        //     }
        //   },
        //   {
        //     featureType: 'land',
        //     elementType: 'all',
        //     stylers: {
        //       color: '#f3f3f3'
        //     }
        //   },
        //   {
        //     featureType: 'railway',
        //     elementType: 'all',
        //     stylers: {
        //       visibility: 'off'
        //     }
        //   },
        //   {
        //     featureType: 'highway',
        //     elementType: 'all',
        //     stylers: {
        //       color: '#fdfdfd'
        //     }
        //   },
        //   {
        //     featureType: 'highway',
        //     elementType: 'labels',
        //     stylers: {
        //       visibility: 'off'
        //     }
        //   },
        //   {
        //     featureType: 'arterial',
        //     elementType: 'geometry',
        //     stylers: {
        //       color: '#fefefe'
        //     }
        //   },
        //   {
        //     featureType: 'arterial',
        //     elementType: 'geometry.fill',
        //     stylers: {
        //       color: '#fefefe'
        //     }
        //   },
        //   {
        //     featureType: 'poi',
        //     elementType: 'all',
        //     stylers: {
        //       visibility: 'off'
        //     }
        //   },
        //   {
        //     featureType: 'green',
        //     elementType: 'all',
        //     stylers: {
        //       visibility: 'off'
        //     }
        //   },
        //   {
        //     featureType: 'subway',
        //     elementType: 'all',
        //     stylers: {
        //       visibility: 'off'
        //     }
        //   },
        //   {
        //     featureType: 'manmade',
        //     elementType: 'all',
        //     stylers: {
        //       color: '#d1d1d1'
        //     }
        //   },
        //   {
        //     featureType: 'local',
        //     elementType: 'all',
        //     stylers: {
        //       color: '#d1d1d1'
        //     }
        //   },
        //   {
        //     featureType: 'arterial',
        //     elementType: 'labels',
        //     stylers: {
        //       visibility: 'off'
        //     }
        //   },
        //   {
        //     featureType: 'boundary',
        //     elementType: 'all',
        //     stylers: {
        //       color: '#fefefe'
        //     }
        //   },
        //   {
        //     featureType: 'building',
        //     elementType: 'all',
        //     stylers: {
        //       color: '#d1d1d1'
        //     }
        //   },
        //   {
        //     featureType: 'label',
        //     elementType: 'labels.text.fill',
        //     stylers: {
        //       color: '#999999'
        //     }
        //   }
        // ]
        //
      },
    },
    series: [
      {
        name: '非遗地址',
        type: 'scatter',
        coordinateSystem: 'bmap',
        data: convertData(mapData),
        symbol: 'pin',
        symbolSize: 35,
        color:dataColor.value,
        encode: {
          value: 2
        },
        label: {
          formatter: '{b}',
          position: 'right',
          show: false
        },
        emphasis: {
          label: {
            show: true
          }
        }
      },
      params
    ]
  };
  option && myChart.setOption(option);
  myChart.on('click',(params) => {
    if (params.data.name === '我'){
      return
    }else{
      const id = params.data.value[2].substring(params.data.value[2].indexOf('@') + 1,params.data.value[2].length)
      router.push({
        name:'heritageDetail',
        params:{
          id:Number(id)
        }
      })
    }
  })
}

onMounted(() => {
  setTimeout(() => {
    timer()
  }, 1500)
})


</script>

<style lang="less" scoped>
.el-radio-button {
  margin-top: 8px;
}
</style>